package com.example.backend.service.impl;

import com.example.backend.entity.StorageRecord;
import com.example.backend.mapper.StorageRecordMapper;
import com.example.backend.service.PortRuleCalculationService;
import com.example.backend.service.StorageFeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class StorageFeeServiceImpl implements StorageFeeService {

    @Autowired
    private StorageRecordMapper recordMapper;
    
    @Autowired
    private PortRuleCalculationService portRuleCalculationService;

    @Override
    @Transactional
    public StorageRecord saveRecord(StorageRecord record) {
        recordMapper.insert(record);
        return record;
    }

    @Override
    public void calculateStorageFee(StorageRecord record) {
        if (record.getEntryTime() == null || record.getSailingDate() == null) {
            return;
        }

        long diffInMillis = record.getSailingDate().getTime() - record.getEntryTime().getTime();
        int storageDays = (int) (diffInMillis / (1000 * 60 * 60 * 24));

        // 使用新的规则计算服务
        BigDecimal fee = portRuleCalculationService.calculateStorageFee(
            record.getCompanyId(), 
            record.getPortId(), 
            record.getEntryWeight(), 
            storageDays
        );
        
        record.setStorageFee(fee);

        // 更新剩余吨量
        if (record.getOutWeight() != null) {
            record.setRemainingWeight(record.getEntryWeight().subtract(record.getOutWeight()));
        }
    }

    @Override
    public List<StorageRecord> getAllRecords() {
        return recordMapper.selectAll();
    }

    @Override
    public List<StorageRecord> getRecordsByDateRange(Date start, Date end) {
        return recordMapper.selectByDateRange(start, end);
    }

    @Override
    public BigDecimal calculateTotalFee() {
        List<StorageRecord> records = recordMapper.selectAll();
        return records.stream()
                .map(StorageRecord::getStorageFee)
                .filter(fee -> fee != null)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public BigDecimal calculateTotalEntryWeight() {
        List<StorageRecord> records = recordMapper.selectAll();
        return records.stream()
                .map(StorageRecord::getEntryWeight)
                .filter(weight -> weight != null)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public BigDecimal calculateTotalOutWeight() {
        List<StorageRecord> records = recordMapper.selectAll();
        return records.stream()
                .map(StorageRecord::getOutWeight)
                .filter(weight -> weight != null)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}